﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
using MySql.Data.MySqlClient;
using Product.Application.Query;
using Product.Common;
using Product.Common.Dto;
using Product.EntityFrameworkCore.PO;

namespace ProductWebApi.Controllers
{
    [Route("api/product/v1/[controller]")]
    [ApiController]
    public class SkuController : ControllerBase
    {
        private readonly ISkuQueryService _skuQueryService;
        public SkuController(ISkuQueryService skuQueryService)
        {
            _skuQueryService = skuQueryService;
        }

        /// <summary>
        /// 扣减库存
        /// </summary>
        /// <returns></returns>
        [HttpPost("stock/cut")]
        public async Task<ResponseResult<string>> DeductionStock(List<SkuDto> skuList)
        {
            if (!skuList.Any())
            {
                return new ResponseResult<string>() { IsSucceed = false, Message = "sku不能为空!" };
            }

            var connectionString = ConfigurationHelper.GetConnectionString();

            using (var connection = new MySqlConnection(connectionString))
            {
                try
                {
                    if (connection.State == ConnectionState.Closed)
                    {
                        await connection.OpenAsync().ConfigureAwait(false);
                    }
                    var sql = string.Empty;
                    foreach (var sku in skuList)
                    {
                        if (string.IsNullOrWhiteSpace(sku.SkuId))
                        {
                            return new ResponseResult<string>() { IsSucceed = false, StatusCode = HttpStatusCode.BadRequest.ToString(), Message = $"{sku.SkuId}:skuId不能为空!" };
                        }

                        if (sku.SkuQuantity == 0)
                        {
                            return new ResponseResult<string>() { IsSucceed = false, StatusCode = HttpStatusCode.BadRequest.ToString(), Message = $"{sku.SkuId}:sku数量不能为0!" };
                        }
                        sql += $"UPDATE t_sku SET Stock=Stock - {sku.SkuQuantity} where Id = '{sku.SkuId}' AND  Stock > {sku.SkuQuantity};";
                    }

                    var transaction = await connection.BeginTransactionAsync();
                    try
                    {
                        var i = await connection.ExecuteAsync(sql, null, transaction);
                        await transaction.CommitAsync();
                        if (i > 0)
                        {
                            return new ResponseResult<string>() { IsSucceed = true, StatusCode = HttpStatusCode.OK.ToString(), Message = "扣减库存成功!" };
                        }
                        else
                        {
                            return new ResponseResult<string>() { IsSucceed = false, StatusCode = HttpStatusCode.BadRequest.ToString(), Message = "扣减库存失败!" };
                        }
                    }
                    catch (Exception ex)
                    {
                        await transaction.RollbackAsync();
                        await transaction.DisposeAsync();
                        throw new Exception(ex.Message);
                    }

                }
                catch (Exception ex)
                {
                    return new ResponseResult<string>() { IsSucceed = false, StatusCode = HttpStatusCode.InternalServerError.ToString(), Message = $"扣减库存失败！{skuList.Select(e => e.SkuId).Join(",")}{ex.Message}" };
                    //throw new Exception($"扣减库存失败！{skuList.Select(e => e.SkuId).Join(",")}{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 获取需要验证的sku
        /// </summary>
        /// <param name="skuIds"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpGet("{skuIds}")]
        public async Task<ResponseResult<List<SkuPo>>> GetVerifySkuList(string skuIds)
        {
            var skuIdList = skuIds.Split(',').ToList();
            var skuList = await _skuQueryService.GetVerifySkuList(skuIdList);
            return new ResponseResult<List<SkuPo>>() { IsSucceed = true, Result = skuList };
        }

        //[Authorize]
        [HttpGet("test")]
        public async Task TestUnique() 
        {
            var claims = HttpContext.User.Claims;
        }


    }
}
